<template>
  <div class="patrol-record-container">
    <div class="patrol-header">
      <h2 class="page-title">巡更记录</h2>
      <div class="filter-container">
        <el-select
            v-model="selectedCommunity"
            placeholder="选择小区"
            @change="loadRecords"
            class="filter-select"
        >
          <el-option
              v-for="community in communityList"
              :key="community.id"
              :label="community.name"
              :value="community.id"
          ></el-option>
        </el-select>
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="loadRecords"
            class="filter-date-picker"
        ></el-date-picker>
        <el-button type="success" class="export-btn" @click="exportRecords">
          <Download /> 导出记录
        </el-button>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
          :data="records"
          border
          stripe
          style="width: 100%;"
          v-loading="loading"
          :header-cell-style="{background:'#f5f7fa', color:'#606266', fontWeight: 'bold'}"
      >
        <el-table-column prop="pointName" label="巡更点位" width="180" />
        <el-table-column prop="categoryName" label="点位分类" width="100" />
        <el-table-column prop="areaName" label="地区名称" width="120" />
        <el-table-column prop="longitude" label="打卡位置经度" width="120" />
        <el-table-column prop="latitude" label="打卡位置纬度" width="120" />
        <el-table-column prop="checkInTime" label="签到时间" width="180" />
        <el-table-column prop="checkInUser" label="签到人员" width="100" />
        <el-table-column prop="result" label="巡检结果" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.result === '正常' ? 'success' : 'danger'" size="large">
              {{ scope.row.result }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="异常说明" min-width="200">
          <template #default="scope">
            <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="viewDetail(scope.row)"
                class="detail-btn"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
        title="巡更记录详情"
        v-model="detailDialogVisible"
        width="650px"
        append-to-body
        class="detail-dialog"
    >
      <el-form :model="detailData" label-width="120px" label-position="right">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="巡更点位">
              <el-input v-model="detailData.pointName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点位分类">
              <el-input v-model="detailData.categoryName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="地区名称">
              <el-input v-model="detailData.areaName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签到人员">
              <el-input v-model="detailData.updateBy" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="打卡位置经度">
              <el-input v-model="detailData.longitude" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="打卡位置纬度">
              <el-input v-model="detailData.latitude" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="签到时间">
              <el-input v-model="detailData.checkInTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检结果">
              <el-input v-model="detailData.result" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="异常说明">
          <el-input type="textarea" v-model="detailData.remark" disabled :rows="3" />
        </el-form-item>
        <el-form-item label="现场照片">
          <!-- 只有当photos数组有值时才渲染轮播图 -->
          <el-carousel height="360px" v-if="detailData.photos.length > 0" arrow="always">
            <el-carousel-item
                v-for="(photo, index) in detailData.photos"
                :key="index"
            >
              <div class="photo-wrapper">  <!-- 新增包装容器 -->
              <!-- 直接绑定photo，无需额外处理 -->
              <img
                  :src="photo"
                  alt="巡检现场照片"
                  class="photo-preview"
                  @error="handleImgError(photo, index)"
              />
              </div>
            </el-carousel-item>
          </el-carousel>
          <!-- 无图片时显示提示 -->
          <div v-else class="no-photo-container">
            <span class="no-photo-text">无现场照片</span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false" class="cancel-btn">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {ref, reactive, onMounted, nextTick} from 'vue'
import { ElMessage, ElMessageBox} from 'element-plus'
import { Plus, ArrowUp, ArrowDown, Download } from '@element-plus/icons-vue'
import { getRecordByCommunity, exportRecord } from '../api/patrolRecord'
import { deleteRoute as deleteRouteApi } from '../api/patrolRoute';
import { getCommunityList } from '../api/community';

export default {
  name: 'PatrolRecord',
  components: {
    Plus, ArrowUp, ArrowDown, Download // 注册下载图标
  },
  setup() {
    // 社区列表
    const communityList = ref([    ])
    // 响应式数据
    const selectedCommunity = ref(1)
    const dateRange = ref([])
    const records = ref([])
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const detailDialogVisible = ref(false)
    const detailData = reactive({
      planName: '',
      routeName: '',
      pointName: '',
      categoryName: '',
      locationNo: '',
      areaName:'',
      longitude:'',
      latitude:'',
      updateBy:'',
      checkInTime: '',
      checkInUser: '',
      result: '',
      remark: '',
      photos: []
    })






    // 加载记录数据
    const loadRecords = async () => {
      try {
        loading.value = true;
        const params = {
          communityId: selectedCommunity.value,
          startTime: dateRange.value[0] ? dateRange.value[0].toISOString() : '',
          endTime: dateRange.value[1] ? dateRange.value[1].toISOString() : '',
          pageNum: currentPage.value,
          pageSize: pageSize.value
        };
        let {data:data} = await getRecordByCommunity(params);
        console.log(data)
        if (data.code === 0) {
          // 后端返回的是wcm_patrol_point_record表的数据，适配前端字段
          records.value = data.data.records.map(item => ({
            ...item,
            checkInTime: item.patrolTime, // 后端patrolTime对应前端checkInTime
            createBy: item.createBy, // 后端createBy对应前端checkInUser
            result: item.patrolResult // 后端patrolResult对应前端result
          }));
          total.value = data.data.total;
        } else {
          ElMessage.error(data.message || '加载记录失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      } finally {
        loading.value = false;
      }
    };
// 加载社区列表
    const loadCommunityList = async () => {
      try {
        let { data: data } = await getCommunityList();
        if (data.code === 0) {
          communityList.value = data.data;
          // 默认选中第一个社区
          if (communityList.value.length > 0) {
            selectedCommunity.value = communityList.value[0].id;
          }
        } else {
          ElMessage.error(data.msg || '加载社区列表失败');
        }
      } catch (error) {
        ElMessage.error('加载社区失败：' + error.message);
      }
    };
    // 分页大小改变
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      loadRecords()
    }

    // 当前页改变
    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      loadRecords()
    }

    // 图片加载失败处理
    const handleImgError = (index) => {
      detailData.photos[index] = '/images/default-photo.png'; // 替换为项目中的默认图片路径
    };
    // 查看详情
    const viewDetail = (record) => {
      try {
        // 先清空之前的图片数据，避免缓存
        detailData.photos = [];
        // 复制基础数据
        Object.assign(detailData, record)
        // 打印原始URL和处理后的数据
        console.log("原始photoUrls:", record.photoUrls);
        const urls = (record.photoUrls || '').split(',').map(url => url.trim()).filter(url => url);
        console.log("处理后的photos:", urls);
        detailData.photos = [...urls];
        // 直接设置为 true
        nextTick(() => {
          detailDialogVisible.value = true;
          // 二次确认图片数据已渲染
          nextTick(() => {
            console.log("弹窗中的photos:", detailData.photos);
          });
        });
        console.log('弹窗状态:', detailDialogVisible.value)
      } catch (error) {
        console.error('查看详情出错:', error)
      }
    }

// 导出记录方法（修改为接收文件流）
    const exportRecords = async () => {
      try {
        loading.value = true;
        // 构造查询参数（社区ID、日期范围）(注意：前端传的是日期字符串，无需转ISO格式)
        const params = {
          communityId: selectedCommunity.value,
          startTime: dateRange.value[0] ? dateRange.value[0].toISOString().split('T')[0] : '',
          endTime: dateRange.value[1] ? dateRange.value[1].toISOString().split('T')[0] : ''
        };

        // 调用导出接口（此时responseType已在api中设置）
        const response = await exportRecord(params);

        // 创建Blob对象并下载（适配不同浏览器）
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        // 处理IE/Edge兼容（可选）
        if (window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, `巡更记录_${new Date().toLocaleDateString()}.xlsx`);
        } else {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `巡更记录_${new Date().toLocaleDateString()}.xlsx`;
          document.body.appendChild(a);
          a.click();
          // 清理资源
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        }
        ElMessage.success('导出成功');
      } catch (error) {
        console.error('导出失败详情:', error);
        ElMessage.error('导出失败：服务器错误或参数错误');
      } finally {
        loading.value = false;
      }
    };

// 组件挂载时先加载社区列表，再加载记录
    onMounted(async () => {
      await loadCommunityList();
      if (communityList.value.length > 0) {
        await loadRecords(); // 社区加载完成后再加载记录
      }
    });

    return {
      communityList,
      selectedCommunity,
      dateRange,
      records,
      loading,
      currentPage,
      pageSize,
      total,
      detailDialogVisible,
      detailData,
      loadRecords,
      handleSizeChange,
      handleCurrentChange,
      viewDetail,
      exportRecords,
      handleImgError
    }
  }
}
</script>

<style scoped>
.patrol-record-container {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  min-height: calc(100vh - 40px);
  overflow: auto;
}

.patrol-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  color: #303133;
  margin: 0;
  font-weight: 600;
  margin-right: 24px;
}

.filter-container {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.filter-select,
.filter-date-picker {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
}

.export-btn {
  border-radius: 6px;
  padding: 10px 20px;
  background: linear-gradient(135deg, #67C23A 0%, #409EFF 100%);
  border: none;
  transition: all 0.3s ease;
}

.export-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__row:hover > td) {
  background-color: #f0f9eb;
}

.no-data {
  color: #909399;
}

.detail-btn {
  width: 70px;
  padding: 8px 0;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.detail-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

/* 弹窗样式 */
.detail-dialog :deep(.el-dialog__header) {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
}

.detail-dialog :deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.detail-dialog :deep(.el-dialog__footer) {
  padding: 10px 24px 20px;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.cancel-btn {
  border-radius: 6px;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background-color: #f2f6fc;
  color: #409EFF;
}

/* 照片预览样式 */
/* 调整轮播图容器高度，让照片有合适展示空间 */
:deep(.el-carousel) {
  height: 360px !important;
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
}
/* 图片居中并覆盖容器 */
.photo-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
/* 调整轮播项里图片的大小 */
:deep(.el-carousel-item) {
  text-align: center; /* 让图片水平居中 */
}
.photo-preview {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.no-photo-text {
  color: #909399;
  font-size: 14px;
}
:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.3);
  width: 36px;
  height: 36px;
  font-size: 18px;
}
:deep(.el-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.5);
}
.no-photo-container {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  border-radius: 4px;
}

/* 轮播图指示器等样式微调 */
:deep(.el-carousel__indicators) {
  display: none !important;
}

:deep(.el-carousel__button) {
  width: 100px;
  height: 600px;
  border-radius: 50%;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    gap: 10px;
  }

  .page-title {
    font-size: 20px;
    margin-right: 16px;
  }
}
</style>